import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from 'components/login/login'

Vue.use(VueRouter)

  const routes = [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/home',
      name: 'home',
      component: () => import("views/home/home.vue"),
      redirect: 'welcome',
      children: [
        {
          path: '/welcome',
          name: 'welcome',
          component: () => import("views/home/child/welcome")
        },
        {
          path: '/users',
          name: 'users',
          component: () => import("views/home/child/users")
        }
      ]
    }
  ]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  if(to.fullPath !== '/login' && !sessionStorage.getItem('token')) {
      next('/login')
  } else {
    next()
  }
})

export default router
